<?php
class MemberController extends BaseController {
	
	/*
	 * controller 魔术方法，此方法不可少
	 */
	function __construct() {
		parent::__construct();

		$action = strtolower($this->action);

		if(!isset($_SESSION['user']) && !in_array($action, array('vcode','index'))) {
			$this->redirect('/member/index');
			die;
		}
	}

	function actionIndex() {
		$error = '';
		if(!empty($_POST['login'])) {
			$memberModel = KJ::M('user');
			$_SESSION['code'] != strtoupper($_POST['login']['vcode']) && $error = '错误的验证码';

			empty($error) && $error = $memberModel->userLogin($_POST['login']);
			
			empty($error) && $this->redirect('/');
		}

		$this->assign(['error'=>$error]);	
		$this->display();
	}

	function actionView() {
		$pageData = array();

		$this->assign($pageData);
		$this->display();
	}

	function actionRegister() {
		$result = true;
		if(!empty($_POST['register'])) {
			$memberModel = KJ::M('user');

			$_SESSION['code'] != strtoupper($_POST['register']['vcode']) && $result = '错误的验证码';

			is_bool($result) && $result = $memberModel->validate($_POST['register']);

			is_bool($result) && $result = $memberModel->checkDataInDatabase($_POST['register']);

			if(is_bool($result)) {
				if($memberModel->insertNewMember($_POST['register'])) {
					$this->redirect('/');
				}
			}
		}

		$this->assign(['error'=>$result]);
		$this->display();
	}

	function actionLogout() {
		$memberModel = KJ::M('user');
		$memberModel->clearLoginInfo();

		header('location:/');
	}

	function actionVcode() {
		$code = KJ::instance(KJ_PATH.'extension/validateCode.class.php', 'ValidateCode');

	    $code->doimg();
	   	$_SESSION["code"] = strtoupper($code->getCode());
	}
}